package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.system.domain.SysRegion;
import com.ruoyi.system.mapper.SysRegionMapper;
import com.ruoyi.system.service.ISysRegionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Optional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author suntf
 * @since 2023-07-30
 */
@Service
public class SysRegionServiceImpl extends ServiceImpl<SysRegionMapper, SysRegion> implements ISysRegionService {



    /**
     * 根据上级编号获取下级，如果为空 返回全部
     * @author: suntf
     * @date: 2023/7/30 上午9:10
     * @param parentId
     * @return java.util.List<com.ruoyi.system.domain.SysRegion>
     */
    @Override
    public List<SysRegion> getRegion(String parentId) {
        String key = CacheConstants.REGION_KEY + parentId;
        List<SysRegion> list = RedisUtils.getCacheList(key);
        if(CollectionUtils.isEmpty(list)) {
            QueryWrapper<SysRegion> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", "1").orderByAsc("sort").select("code,name,parent_code");
            queryWrapper.eq(StringUtils.isNoneBlank(parentId), "parent_code", parentId);
            list = this.list(queryWrapper);
            RedisUtils.setCacheList(key, list);
            return list;
        }
        return list;
    }

    @Override
    public SysRegion getRegionByCode(String code) {
        if(StringUtils.isBlank(code)) {
            return new SysRegion();
        }
        String key = CacheConstants.REGION_INFO_KEY + code;
        SysRegion cacheObject = RedisUtils.getCacheObject(key);
        if(!Optional.ofNullable(cacheObject).isPresent() || StringUtils.isBlank(cacheObject.getCode())) {
            QueryWrapper<SysRegion> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("code", code);
            SysRegion one = getOne(queryWrapper);
            RedisUtils.setCacheObject(key, one);
            cacheObject = one;
        }
        return cacheObject;
    }

    public static void main(String[] args) {
        SysRegion sysRegion = null;
        System.out.println(Optional.ofNullable(sysRegion).isPresent());
        System.out.println("dd:" + Optional.of(sysRegion).isPresent());
        //sysRegion.setCode("1");
        //System.out.println("cc:"+Optional.of(sysRegion).isPresent());
    }
}
